package net.dreamlu.system.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.extern.slf4j.Slf4j;
import net.dreamlu.common.base.BaseController;
import net.dreamlu.common.qrcode.QRCodeUtil;
import net.dreamlu.mica.core.result.R;

/**
 * @Title: PayController.java
 * @Package net.dreamlu.system.web
 * @Description: 支付
 * @author lambert.wang
 * @date 2019年11月15日 下午3:37:21
 * @since JDK 1.8
 * @version V1.0
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController extends BaseController {
	private static final String UrlStr = "QRCode/";

	private static final String wechatPay = "wechatPay/";

	private static final String aliPay = "aliPay/";

	@GetMapping("/manager")
	public String manager() {
		return "system/pay/payList";
	}

	@GetMapping("qrcode.jpg")
	public ResponseEntity<Resource> captcha(HttpServletResponse response) throws Exception {
		String text = "http://192.168.0.101:8080/web/pay/QRCode";
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		QRCodeUtil.encode(text, null, true, out);
		Resource resource = new ByteArrayResource(out.toByteArray());
		HttpHeaders headers = new HttpHeaders();
		headers.setPragma("no-cache");
		headers.setCacheControl("no-cache");
		headers.setExpires(0);
		headers.setContentType(MediaType.IMAGE_JPEG);
		return new ResponseEntity<>(resource, headers, HttpStatus.OK);
	}

	@RequestMapping("/QRCode")
	public String QRCode(HttpServletRequest request, HttpServletResponse response) {
		log.info("####################请求开始####################");
		String userAgent = request.getHeader("user-agent");
		String RequestURL = request.getRequestURL().toString();
		log.info("URL : " + RequestURL);
		String ReqInfo = RequestURL.substring(RequestURL.indexOf(UrlStr) + UrlStr.length());
		log.info("URL : " + ReqInfo);
//		CommonConfig commonConfig = new CommonConfig();
		if (userAgent != null && userAgent.contains("AlipayClient")) {
			log.info("来自支付宝");
//			String redirecturi = HttpUtils.urlEnCode(commonConfig.getDomain() + aliPay + ReqInfo);
//			log.info("REDIRECT_URI=" + redirecturi);
//			SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay);
//			MyAliPayConfig aliPayConfig = new MyAliPayConfig();
//			aliPayConfig.setAppId(channel.getAppid());
			// 授权页面地址
//			String requestUrl = aliPayConfig.getAuthgateway();
//			requestUrl = requestUrl.replace("APPID", aliPayConfig.getAppId()).replace("SCOPE", aliPayConfig.getScope()).replace("REDIRECT_URI", redirecturi);
			// 重定向到授权页面
//			response.sendRedirect(requestUrl);
			try {
				response.sendRedirect("HTTPS://QR.ALIPAY.COM/FKX04300IARELZHC4CP01B");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (userAgent != null && userAgent.contains("MicroMessenger")) {
			log.info("来自微信");
//			String redirecturi = HttpUtils.urlEnCode(commonConfig.getDomain() + wechatPay + ReqInfo);
//			log.info("REDIRECT_URI=" + redirecturi);
//			SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Wechat);
//			WXPublicConfig publicConfig = new WXPublicConfig();
//			publicConfig.setAppId(channel.getAppid());
//			publicConfig.setOriginId(channel.getOriginid());
//			publicConfig.setAppSecret(channel.getAppsecret());
//			publicConfig.setEncodingAESKey(channel.getEncodingaeskey());
//			// 授权页面地址
//			String requestUrl = publicConfig.getAuthorizeinterface();
//			requestUrl = requestUrl.replace("APPID", publicConfig.getAppId()).replace("REDIRECT_URI", redirecturi).replace("SCOPE", publicConfig.getScope()).replace("STATE",
//					publicConfig.getState());
			// 重定向到授权页面
//			response.sendRedirect(requestUrl);
			try {
				ServletOutputStream out = response.getOutputStream();
				QRCodeUtil.encode("wxp://f2f0Z3eQvaoQ4dXAiI1dzJ5TDvANaQCSBIBJ", null, true, out);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			log.info("未知来源");
		}
		log.info("####################请求结束####################");
		return null;
	}

	@PostMapping("/aliPay")
	public String aliPay() {

		return null;
	}

	@PostMapping("/wechatPay")
	public String wechatPay() {

		return null;
	}

	/**
	 * @Title: aliPayNotify @Description: (支付宝支付成功过回调) @author chenkun @return
	 *         参数 @return String 返回类型 @throws
	 */
	@RequestMapping(value = "/notify", method = RequestMethod.POST)
	@ResponseBody
	public R<Object> aliPayNotify(HttpServletRequest request, HttpServletResponse response) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		
		log.info("request:{}", request);
		request.getParameter("time");
		return status(true);
	}

}
